package com.ruoyi.project.purchase.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.domain.ResultBean;
import com.ruoyi.project.inventory.domain.RyInventory;
import com.ruoyi.project.inventory.service.IRyInventoryService;
import com.ruoyi.project.purchase.domain.RyDepotDetail;
import com.ruoyi.project.purchase.domain.RyDepotHead;
import com.ruoyi.project.purchase.domain.pojo.*;
import com.ruoyi.project.purchase.service.*;
import com.ruoyi.project.warehouse.domain.RyDepotItem;
import com.ruoyi.project.warehouse.domain.RyInventoryCurrentStock;
import com.ruoyi.project.warehouse.domain.WareCurrentStock;
import com.ruoyi.project.warehouse.service.IRyDepotItemService;
import com.ruoyi.project.warehouse.service.IWareCurrentStockService;
import com.ruoyi.project.warehouse.service.IWareInventoryTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname infcController
 * @Description TODO
 * @Date 2022/9/23 18:04
 * @Created by You
 */

@Anonymous
@RestController
@RequestMapping("/infc")
public class InfcController {

    @Autowired
    private IWareInventoryTypeService wareInventoryTypeService;

    @Autowired
    private IRyDepotDetailService ryDepotDetailService;

    @Autowired
    private IRyInventoryService ryInventoryService;
    @Autowired
    private IWareCurrentStockService wareCurrentStockService;

    @Autowired
    private IRyDepotHeadService ryDepotHeadService;

    @Autowired
    private IRyQualityService ryQualityService;

    @Autowired
    private IRyDepotItemService ryDepotItemService;

    @Autowired
    private IRyPurchaseInService ryPurchaseInService;

    @Autowired
    private IRyPurchaseOutService ryPurchaseOutService;

    @Autowired
    private IProjectClearanceService projectClearanceService;

    /**
     * 处理导入的excel数据
     * @param list
     * @return
     */
    @RequestMapping("/dataProcess")
    public ResultBean dataProcess(@RequestBody List<InventoryData> list)
    {

        ResultBean resultBean = new ResultBean();
        System.out.println("dsfs:"+ list);
        //创建列表存放物品表中不存在的数据
        List<InventoryData> nonexistentList = new ArrayList<InventoryData>();

        //创建列表存放wbs不存在的数据
        List<InventoryData> wbsNonexistentList = new ArrayList<InventoryData>();

        //创建需要返回前端处理后的数据列表
        List<RyDepotDetail> returnList = new ArrayList<RyDepotDetail>();

        //处理Excel中的数据
        List<InventoryData> dataList = process(list);
        //遍历数据，查询列表中物品对应信息及总库中当前库存
        for(InventoryData inventoryData : dataList){
            //采购总清单明细表
            RyDepotDetail ryDepotDetail = new RyDepotDetail();
//            ryDepotDetail.setSupply(inventoryData.getSupplier());//excel表中供应商
            ryDepotDetail.setBrand(inventoryData.getSupplier());//excel表中品牌
            ryDepotDetail.setAdvancePurchaseNum(inventoryData.getNumber());//待采购数量

            //判断wbs编码是否存在
            if(StringUtils.isBlank(inventoryData.getWbs())){
                wbsNonexistentList.add(inventoryData);
//                continue;
            }

            //1.首先根据物品编码和名称查出数据库中维护的物品id
            RyInventory ryInventory = ryInventoryService.selectInfoByNameSpeci(inventoryData.getSpec(),inventoryData.getName());
            //判断物品是否存在，不存在就放在nonexistentList中
            if(ryInventory == null){
                nonexistentList.add(inventoryData);
                continue;//这里continue是因为如果物品信息不存在就不能进行下面的2操作，因为物品id不存在
            }
            ryDepotDetail.setInventoryId(ryInventory.getId());//物品id
            ryDepotDetail.setInventoryName(ryInventory.getName());//物品名称
            ryDepotDetail.setInventorySpecifications(ryInventory.getSpecifications());//物品规格
            ryDepotDetail.setWbs(ryInventory.getWbs());//wbs编码
            ryDepotDetail.setUnitPrice(ryInventory.getUnitPrice());//单价

            //2.根据物品id和总仓库id查询总库库物品当前库存量以及相关信息(总库id为1)
            RyInventoryCurrentStock ryInventoryCurrentStock = new RyInventoryCurrentStock();
            ryInventoryCurrentStock.setInventoryId(ryInventory.getId());//物品id
            ryInventoryCurrentStock.setDepotId(1L);//仓库id
            WareCurrentStock wareCurrentStock = wareCurrentStockService.getInfoByDepotInventoryId(ryInventoryCurrentStock);
            if(wareCurrentStock == null){
                ryDepotDetail.setUsableNum(Double.valueOf(0));//总库可用数量
            } else {
                //如果不为空则判断是否存在锁定数量
                RyDepotItem param = new RyDepotItem();
                param.setInventoryId(ryInventory.getId());
                param.setDepotId(1L);
                RyDepotItem result = ryDepotItemService.getLockNumById(param);
                if(result != null){//不为空，存在锁定数量
                    ryDepotDetail.setUsableNum(wareCurrentStock.getCurrentNumber() - result.getOperNumber());//总库可用数量 - 锁定
                } else {
                    ryDepotDetail.setUsableNum(wareCurrentStock.getCurrentNumber());//总库可用数量
                }
            }

            returnList.add(ryDepotDetail);
        }
        System.out.println("------returnList---->" + returnList);

        //如果wbs编码不存在列表或是物品信息表中不存在列表中有值则返回错误提示
        if(wbsNonexistentList.size() != 0 || nonexistentList.size() != 0){
            resultBean.setCode("001");
            String msg = "";
//            String wbsNonexistentStr = "";
//            String nonexistentStr = "";
            if(wbsNonexistentList.size() != 0){
                msg += "wbs不存在:" + JSON.toJSONString(wbsNonexistentList);

            }
            if(nonexistentList.size() != 0){
                msg += "物品信息不存在:" + JSON.toJSONString(nonexistentList);
            }
            resultBean.setMsg(msg);
            return resultBean;
        }

        //成功返回
        resultBean.setData(returnList);
        return resultBean;
    }

    //处理数据
    public List<InventoryData> process(List<InventoryData> list){
        System.out.println("dataList:"+list);
        System.out.println("length:-->" + list.size());
        //创建新数组用来存放去重后的数据
        List<InventoryData> newList = new ArrayList<InventoryData>();

        for(InventoryData inventoryData : list){
            System.out.println("111");
            if(newList.size() == 0){
                System.out.println("222");
                newList.add(inventoryData);
            } else {
                System.out.println("---------length:-->" + newList.size());
                boolean isExit = false;//判断此条参数数据是否存在新列表中
                for(InventoryData newOne : newList){
                    System.out.println("333");
                    //如果参数列表中有和新列表中数据相同的，就合并数量
                    System.out.println("-----------:-->" + inventoryData.getName() + ","+ newOne.getName() + ","+ inventoryData.getSpec() + ","+ newOne.getSpec());

                    if(inventoryData.getName().equals(newOne.getName()) && inventoryData.getSpec().equals(newOne.getSpec())){
                        newOne.setNumber(newOne.getNumber() + inventoryData.getNumber());
                        isExit = true;//设置存在相同数据
                        break;
                    }
                }
                //新数据遍历结束判断
                if(isExit){//如果存在重复就将此参数重置，以便下条数据使用
                    isExit = false;
                } else {//不存在就新增到新数组中
                    newList.add(inventoryData);
                }

            }
        }

        System.out.println("newList:-->" + newList);
        System.out.println("length:-->" + newList.size());

        return newList;
    }


    /**
     * --项目总清单
     * 新增项目总清单及项目总清单子表信息
     * @return
     * @throws Exception
     */
//    @RequestMapping("/addDepotHeadAndDetail")
//    public AjaxResult addDepotHeadAndDetail(@RequestBody DepotDetailBean depotDetailBean)
//    {
//        System.out.println("depotDetailBean---->" + depotDetailBean);
//        return ryDepotHeadService.addDepotHeadAndDetail(depotDetailBean);
//    }


    /**
     * --项目总清单
     * 获取项目总清单详细信息
     */
//    @GetMapping(value = "/selectByDepotId/{id}")
//    public AjaxResult selectByDepotId(@PathVariable("id") Long id)
//    {
//        return AjaxResult.success(ryDepotHeadService.selectRyDepotDetailByDepotId(id));
//    }


    /**
     * --项目总清单
     * 修改项目总清单
     */
//    @RequestMapping("/editDepotHeadAndDetail")
//    public AjaxResult editDepotHeadAndDetail(@RequestBody DepotDetailBean depotDetailBean)
//    {
//        ResultBean resultBean = new ResultBean();
//        return ryDepotHeadService.editDepotHeadAndDetail(depotDetailBean);
//    }


    /**
     *  -- 质检
     * 根据主表修改单据子表信息
     */
//    @RequestMapping("/editQualityDetail")
//    public AjaxResult editQualityDetail(@RequestBody DepotDetailBean depotDetailBean){
//        System.out.println("depotDetailBean---->" + depotDetailBean);
//        return ryQualityService.editDepotDetail(depotDetailBean);
//    }


    /**
     * --采购入库
     * 根据主表修改单据子表信息
     */
    @RequestMapping("/editPurchaseInDetail")
    public AjaxResult editPurchaseInDetail(@RequestBody DepotHeadItem depotHeadItem){
        System.out.println("depotHeadItem---->" + depotHeadItem);
        return ryPurchaseInService.editDepotDetail(depotHeadItem);
    }

    /**
     * --采购入库
     * 单条数据入库
     */
    @RequestMapping("/insertOneDetail")
    public AjaxResult insertOneDetail(@RequestBody RyDepotDetail ryDepotDetail){
        System.out.println("ryDepotDetail---->" + ryDepotDetail);
        return ryPurchaseInService.insertOneDetail(ryDepotDetail);
    }

    /**
     * --采购入库
     * 获取单据主表详细信息
     */
    @GetMapping(value = "/selectDetailByDepotId/{id}")
    public AjaxResult selectDetailByDepotId(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ryPurchaseInService.selectRyDepotDetailByDepotId(id));
    }


    /**
     * --采购出库
     * 获取单据主表详细信息
     */
    @GetMapping(value = "/selectOutDetailByDepotId/{id}")
    public AjaxResult selectOutDetailByDepotId(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ryPurchaseOutService.selectRyDepotDetailByDepotId(id));
    }

    /**
     * --采购出库
     * 根据主表修改单据子表信息
     */
    @RequestMapping("/editPurchaseOutDetail")
    public AjaxResult editPurchaseOutDetail(@RequestBody DepotHeadItem depotHeadItem){
        System.out.println("depotHeadItem---->" + depotHeadItem);
        return ryPurchaseOutService.editDepotDetail(depotHeadItem);
    }

    /**
     * --采购出库
     * 单条数据出库
     */
    @RequestMapping("/oneOutDetail")
    public AjaxResult oneOutDetail(@RequestBody RyDepotDetail ryDepotDetail){
        System.out.println("ryDepotDetail---->" + ryDepotDetail);
        return ryPurchaseOutService.oneOutDetail(ryDepotDetail);
    }


    /**
     * --项目清仓
     * 本质上是项目库出库，总库入库操作
     * 要记录出入库记录
     * 根据主表修改单据子表信息
     */
    @RequestMapping("/editProjectClearance")
    public AjaxResult editProjectClearance(@RequestBody DepotHeadItem depotHeadItem){
        System.out.println("depotHeadItem---->" + depotHeadItem);
        return  projectClearanceService.editProjectClearance(depotHeadItem);
    }


    /**
     * 新增明细数据时
     * 查询物品关联信息
     */
    @RequestMapping("/getInfoByInventory")
    public ResultBean getInfoByInventory(@RequestBody InventoryBean inventoryBean){
        ResultBean resultBean = new ResultBean();
        System.out.println("inventoryBean---->" + inventoryBean);
        //采购总清单明细表
        RyDepotDetail ryDepotDetail = new RyDepotDetail();
        ryDepotDetail.setSupply(inventoryBean.getSupply());//供应商
        ryDepotDetail.setAdvancePurchaseNum(Double.valueOf(0));//待采购数量
        ryDepotDetail.setInventoryId(inventoryBean.getId());//物品id
        ryDepotDetail.setInventoryName(inventoryBean.getName());//物品名称
        ryDepotDetail.setInventorySpecifications(inventoryBean.getSpecifications());//物品规格
        ryDepotDetail.setWbs(inventoryBean.getWbs());//wbs编码
        ryDepotDetail.setUnitPrice(inventoryBean.getUnitPrice());

        //根据物品id和总仓库id查询总库库物品当前库存量以及相关信息(总库id为1)
        RyInventoryCurrentStock ryInventoryCurrentStock = new RyInventoryCurrentStock();
        ryInventoryCurrentStock.setInventoryId(inventoryBean.getId());//物品id
        ryInventoryCurrentStock.setDepotId(1L);//仓库id
        WareCurrentStock wareCurrentStock = wareCurrentStockService.getInfoByDepotInventoryId(ryInventoryCurrentStock);
        if(wareCurrentStock == null){
            ryDepotDetail.setUsableNum(Double.valueOf(0));//总库可用数量
        } else {
            ryDepotDetail.setUsableNum(wareCurrentStock.getCurrentNumber());//总库可用数量
        }

        //成功返回
        resultBean.setData(ryDepotDetail);
        return resultBean;
    }





    /**
     * 查询已入库数量和已入库记录数
     */
    @GetMapping("/getInCount")
    public void getNumByDepotInventoryId(){
        RyDepotItem ryDepotItem = new RyDepotItem();
        ryDepotItem.setDepotId(1L);//总库
        ryDepotItem.setInventoryId(10L);

        Long num = ryDepotItemService.getNumByDepotInventoryId(ryDepotItem);
        int count = ryDepotItemService.getCountByDepotInventoryId(ryDepotItem);

        System.out.println("num:count--->" + num + "," + count);
    }


    /**
     * 查询1级类别：种类
     */
    @GetMapping("/allKindType")
    public AjaxResult allKindType(){
        return AjaxResult.success(wareInventoryTypeService.allKindType());
    }


    /**
     * 根据父类id查询其下子类别
     */
    @GetMapping("/findByParentId/{id}")
    public AjaxResult findByParentId(@PathVariable("parentId") Long parentId){
        return AjaxResult.success(wareInventoryTypeService.findByParentId(parentId));
    }


    /**
     * 查询可以生成订单的项目明细数据：就是purchase_order_id为空的
     */
    @GetMapping("/selectDetailForOrder")
    public AjaxResult selectDetailForOrder(@RequestBody ParamBean paramBean){
        return AjaxResult.success(ryDepotDetailService.selectDetailForOrder(paramBean));
    }


}
